<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Helpers\SortHelper;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\ChPermission;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Constants\SendRecordStatusConstants;
use App\CustHub\Dto\OperationLogDto;
use App\CustHub\Event\ChOperationLog;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChCrowdSending;
use App\CustHub\Model\ChCrowdSendingGroup;
use App\CustHub\Model\ChCrowdSendingLoop;
use App\CustHub\Model\ChCrowdSendingSubTask;
use App\CustHub\Model\ChRoom;
use App\CustHub\Model\ChSendRecord;
use App\CustHub\Model\ChWord;
use App\CustHub\Model\ChWordGroup;
use App\CustHub\Service\ChContactService;
use App\CustHub\Service\ChCrowSendingService;
use App\CustHub\Service\ChRobotApplyService;
use App\CustHub\Service\ChRobotService;
use App\CustHub\Service\ChRoomService;
use App\CustHub\Service\ChSendConfigService;
use App\Enum\WordTypeEnum;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use App\CustHub\Service\ChUserService;
use Hyperf\Di\Annotation\Inject;

#[Controller(prefix: 'ch/crowd/sending'), ApiAuth, VerifySignature]
class CrowdSendingController extends BaseController
{

    #[Inject]
    protected ChSendConfigService $sendService;

    #[Inject]
    protected ChCrowSendingService $crowSendService;

    #[Inject]
    protected ChRobotApplyService $applyService;

    #[Inject]
    protected ChRobotService $robotService;

    #[Inject]
    protected ChContactService $contactService;

    #[Inject]
    protected ChRoomService $roomService;


    /**
     * 添加分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/add'), ChPermission('ch:crowd:sending:group:add')]
    public function addGroup()
    {
        $this->validateParam([
            'title' => 'required',
            'crowd_type' => 'required'
        ]);
        $uid = $this->request->input('uid');
        $title = $this->request->input('title');
        $mainUid = $this->request->input('main_uid');
        $pId = $this->request->input('p_id', 0);
        $crowdType = $this->request->input('crowd_type');
        $res = ChCrowdSendingGroup::saveGroup($uid, $mainUid, $title, $crowdType, $pId);
        return $this->success('添加成功', $res);
    }

    /**
     * 修改分组
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/edit'), ChPermission('ch:crowd:sending:group:edit')]
    public function editGroup()
    {
        $this->validateParam([
            'title' => 'required',
            'crowd_type' => 'required'
        ]);
        $uid = $this->request->input('uid');
        $title = $this->request->input('title');
        $id = $this->request->input('id');
        $pId = $this->request->input('p_id', 0);
        $mainUid = $this->request->input('main_uid');
        $crowdType = $this->request->input('crowd_type');

        $res = ChCrowdSendingGroup::saveGroup($uid, $mainUid, $title, $crowdType, $pId, $id);
        return $this->success('修改成功', $res);
    }


    #[PostMapping('group/delete'), ChPermission('ch:crowd:sending:group:edit')]
    public function deleteGroup()
    {
        $this->validateParam([
            'id' => 'required',
            //'type' => 'required',
        ]);
        $id = $this->request->input('id');
        //$type = $this->request->input('type');
        //1删除分组及话术 2删除分组
//        if ($type == 1) {
//            Db::transaction(function () use ($id) {
//                ChCrowdSendingGroup::query()->where('id', $id)->delete();
//                $ids = ChCrowdSendingGroup::query()->where('p_id', $id)->pluck('id');
//                $ids = !empty($ids) ? $ids : [];
//                $ids[] = $id;
//                ChCrowdSendingGroup::query()->where('p_id', $id)->delete();
//                ChCrowdSending::query()->whereIn('group_id', $ids)->delete();
//            });
//
//        } else {
//            Db::transaction(function () use ($id) {
//                ChCrowdSendingGroup::query()->where('id', $id)->delete();
//                $ids = ChCrowdSendingGroup::query()->where('p_id', $id)->pluck('id');
//                $ids = !empty($ids) ? $ids : [];
//                $ids[] = $id;
//                ChCrowdSendingGroup::query()->where('p_id', $id)->delete();
//                ChCrowdSending::query()->whereIn('group_id', $ids)->update(['group_id' => 0]);
//            });
//        }

        Db::transaction(function () use ($id) {
            ChCrowdSendingGroup::query()->where('id', $id)->delete();
            $ids = ChCrowdSendingGroup::query()->where('p_id', $id)->pluck('id');
            $ids = !empty($ids) ? $ids : [];
            $ids[] = $id;
            ChCrowdSendingGroup::query()->where('p_id', $id)->delete();
            ChCrowdSending::query()->whereIn('group_id', $ids)->update(['group_id' => 0]);
        });
        return $this->success('删除成功', []);
    }


    #[PostMapping('delete'), ChPermission('ch:crowd:sending:delete')]
    public function delete()
    {
        $this->validateParam([
            'id' => 'required',
            //'type' => 'required',
        ]);
        $id = $this->request->input('id');
        ChCrowdSending::query()->where('id', $id)->delete();
        ChCrowdSendingSubTask::query()->where('is_loop', 0)->where('crowd_sending_id',$id)->delete();
        return $this->success('删除成功', []);
    }

    #[PostMapping('loop/delete'), ChPermission('ch:crowd:sending:loop:delete')]
    public function deleteLoop()
    {
        $this->validateParam([
            'id' => 'required',
            //'type' => 'required',
        ]);
        $id = $this->request->input('id');
        ChCrowdSendingLoop::query()->where('id', $id)->delete();
        ChCrowdSendingSubTask::query()->where('is_loop', 1)->where('crowd_sending_id',$id)->delete();
        return $this->success('删除成功', []);
    }

    /**
     * 分组列表
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('group/list'), ChPermission('ch:crowd:sending:group:list')]
    public function groupList()
    {
        $uid = $this->request->input('uid');
        $crowd_type = $this->request->input('crowd_type');
        $page_size = $this->request->input('page_size', 15);
        $mainUid = $this->request->input('main_uid');

        $page = ChCrowdSendingGroup::query()->where('main_uid', $mainUid)->where('p_id', 0)->where('crowd_type', $crowd_type)->orderByDesc('sort')->paginate((int)$page_size);
        $list = $page->items();
        $total = $page->total();
        return $this->success('获取成功', ['list' => $list, 'total' => $total]);
    }


    #[PostMapping('add'), ChPermission('ch:crowd:sending:add')]
    public function add()
    {
        $this->validateParam([
            'title' => 'required',
            'content' => 'required',
            'crowd_type' => 'required',
            'task_type' => 'required',
            'robot_ids' => 'required',
            //'corp_id' => 'required',
            'send_type' => 'required',
//            'custom_ids' => 'required_if:send_type,1',
//            'crowd_ids' => 'required_if:send_type,1',
//            'condition_conf' => 'required_if:send_type,2',
            'is_send_loss' => 'required',
            'exception_type' => 'required_if:crowd_type,1',
            'send_limit_type' => 'required',
            'send_limit_conf' => 'required_if:send_limit_type,2',
            'send_times' => 'required',
            'send_times_conf' => 'required_unless:send_times,1',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $params = $this->request->all();
        $sendTimes = $this->request->input('send_times');
        $res = $this->crowSendService->createTask($uid, $mainUid, $params);
        return $this->success('添加成功', $res);
    }


    #[PostMapping('editGroup'), ChPermission('ch:crowd:sending:edit:group')]
    public function editSendingGroup()
    {
        $this->validateParam([
            'id' => 'required',
            'group_id' => 'required',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $group_id = $this->request->input('group_id');
        $is_loop = $this->request->input('is_loop');
        $params = $this->request->all();
        if($is_loop){
            ChCrowdSendingLoop::where('id',$id)->update(['group_id'=>$group_id]);
        }else{
            ChCrowdSending::where('id',$id)->update(['group_id'=>$group_id]);
        }
        return $this->success('修改成功');
    }

    #[PostMapping('edit'), ChPermission('ch:crowd:sending:edit')]
    public function edit()
    {
        $this->validateParam([
            'id' => 'required',
            'title' => 'required',
            'content' => 'required',
            'crowd_type' => 'required',
            'task_type' => 'required',
            'send_type' => 'required',
//            'custom_ids' => 'required_if:send_type,1',
//            'crowd_ids' => 'required_if:send_type,1',
//            'condition_conf' => 'required_if:send_type,2',
            'is_send_loss' => 'required',
            'exception_type' => 'required_if:crowd_type,1',
            'send_limit_type' => 'required',
            'send_limit_conf' => 'required_if:send_limit_type,2',
            'send_times' => 'required',
            'send_times_conf' => 'required_unless:send_times,1',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $params = $this->request->all();
        if($params['send_type']==1 && empty($params['crowd_ids']) && empty($params['custom_ids'])){
            return $this->error('请选择发送目标');
        }
        $res = Db::transaction(function () use ($uid, $mainUid, $params, $id) {
            $targetIds = [$id];
            $robotIds = !is_array($params['robot_ids']) ? json_decode($params['robot_ids'], true) : $params['robot_ids'];
            $robotIds && $this->applyService->batchApply($params['corp_id'], $params['crowd_type'], $targetIds, $robotIds, false);
            return ChCrowdSending::saveCrowSending($uid, $mainUid, $params, $id);
        });
        $type=$params['send_type']==1?101:102;
        event((new ChOperationLog(
            (new OperationLogDto())
                ->setUid($uid)
                ->setMainUid($mainUid)
                ->setSchemeId($res->id)
                ->setName($params['title'])
                ->setContent('编辑群发任务')
                ->setType($type)
        )));
        return $this->success('添加成功', $res);
    }

    #[PostMapping('loop/edit'), ChPermission('ch:crowd:sending:loop:edit')]
    public function editLoop()
    {
        $this->validateParam([
            'id' => 'required',
            'title' => 'required',
            'content' => 'required',
            'crowd_type' => 'required',
            'task_type' => 'required',
            'send_type' => 'required',
//            'custom_ids' => 'required_if:send_type,1',
//            'crowd_ids' => 'required_if:send_type,1',
//            'condition_conf' => 'required_if:send_type,2',
            'is_send_loss' => 'required',
            'exception_type' => 'required_if:crowd_type,1',
            'send_limit_type' => 'required',
            'send_limit_conf' => 'required_if:send_limit_type,2',
            'send_times' => 'required',
            'send_times_conf' => 'required_unless:send_times,1',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $params = $this->request->all();
        if($params['send_type']==1 && empty($params['crowd_ids']) && empty($params['custom_ids'])){
            return $this->error('请选择发送目标');
        }
        $res = ChCrowdSendingLoop::saveCrowSendingLoop($uid, $mainUid, $params, $id);
        $targetIds = [$res->id];
        $robot_ids=!is_array($params['robot_ids']) ? json_decode($params['robot_ids'],true):$params['robot_ids'];
        $robot_ids && $this->applyService->batchApply($params['corp_id'], SendConfigConstants::SENDING_LOOP, $targetIds, $robot_ids, false);
        $type=$params['send_type']==1?101:102;
        event((new ChOperationLog(
            (new OperationLogDto())
                ->setUid($uid)
                ->setMainUid($mainUid)
                ->setSchemeId($res->id)
                ->setName($params['title'])
                ->setContent('编辑群发循环任务')
                ->setType($type)
        )));
        return $this->success('添加成功', $res);
    }



    #[PostMapping('detail'), ChPermission('ch:crowd:sending:detail')]
    public function detail()
    {
        $this->validateParam([
            'id' => 'required',
        ]);
        $id = $this->request->input('id');
        $res = ChCrowdSending::query()->with(['corp'=>function($q){
            $q->select('id','corp_name','corp_log');
        },'group' => function ($q) {
            $q->select('id', 'title', 'p_id');
        }])->where('id', $id)->first() -> toArray();
        $robots = $this -> applyService -> getApplyRobotsInfo($res['crowd_type'],$res['id']) -> toArray();
        $res['robots'] = $robots;
        $res['condition_conf'] = $this -> crowSendService->formatConditionToText($res['condition_conf']);
        if(!empty($res['custom_ids'])){
            $contactInfo=getContactIds($res['custom_ids']);
            $res['custom_ids_array'] = $this -> contactService -> getContactByUserIds($contactInfo['contacts']);
        }
        if(!empty($res['crowd_ids'])){
            $contactInfo=getContactIds($res['crowd_ids']);
            $res['crowd_ids_array'] = $this -> roomService -> getRoomsByUserIds($contactInfo['contacts']);
        }
        return $this->success('获取成功', $res);
    }


    #[PostMapping('loop/detail'), ChPermission('ch:crowd:sending:loop:detail')]
    public function loopDetail()
    {
        $this->validateParam([
            'id' => 'required',
        ]);
        $id = $this->request->input('id');
        $res = ChCrowdSendingLoop::query()->with(['corp'=>function($q){
            $q->select('id','corp_name','corp_log');
        },'group' => function ($q) {
            $q->select('id', 'title', 'p_id');
        }])->where('id', $id)->first();
        $robots = $this -> applyService -> getApplyRobotsInfo(SendConfigConstants::SENDING_LOOP,$res['id']) -> toArray();
        $res['robots'] = $robots;
        $res['condition_conf'] = $this -> crowSendService->formatConditionToText($res['condition_conf']);
        if(!empty($res['custom_ids'])){
            $contactInfo=getContactIds($res['custom_ids']);
            $res['custom_ids_array'] = $this -> contactService -> getContactByUserIds($contactInfo['contacts']);
        }
        if(!empty($res['crowd_ids'])){
            $contactInfo=getContactIds($res['crowd_ids']);
            $res['crowd_ids_array'] = $this -> roomService -> getRoomsByUserIds($contactInfo['contacts']);
        }
        return $this->success('获取成功', $res);
    }


    #[PostMapping('list'), ChPermission('ch:crowd:sending:list')]
    public function list()
    {
        $params = $this->request->all();
        $uid = $this->request->input('uid');
        $page_size = $this->request->input('page_size', 15);
        $mainUid = $this->request->input('main_uid');
        $crowd_type = $this->request->input('crowd_type');
        $status = $this->request->input('status');
        $date = $this->request->input('date', '');
        if(filled($crowd_type)){
            $where = ['crowd_type' => $crowd_type];
        }
        $accountId = $this->request->input('account_id', 0);
        if (!empty($accountId)) {
            $where[] = ['uid', '=', $accountId];
        } else {
            $where[] = ['main_uid', '=', $mainUid];
        }
        if (!empty($params['group_id'])) {
            $where[] = ['group_id', '=', $params['group_id']];
        }
        if (!empty($params['keyword'])) {
            $where[] = ['title', 'like', "%" . $params['keyword'] . "%"];
        }
        if (!empty($params['send_times'])) {
            $where[] = ['send_times', '=', $params['send_times']];
        }
        if (not_empty($status)) {
            $where[] = ['status', '=', $params['status']];
        }


        $build = ChCrowdSending::query()->with(['group' => function ($q) {
            $q->select('id', 'title', 'p_id');
        },'user' => function ($q) {
            $q->select('id', 'nickname');
        }])->select(['id','title','group_id','content','msg_types','status','start_time','created_at','custom_total','lose_total','crowd_total','success_total','fail_total',
                'complete_total','end_time','uid','main_uid','send_times','is_send_loss','exception_type','send_limit_conf','send_limit_type','condition_conf','crowd_type','speed_text'])
            ->where($where);

        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $build -> whereBetween('created_at',[$params['start_time'], $params['end_time']]);
        } elseif(!empty($date)){
            $build->whereRaw("DATE_FORMAT(start_time, '%Y-%m-%d') = '$date'");
        }else{
            if (not_empty($params['is_recently'])) {
                if ($params['is_recently'] == 1) {
                    $build -> whereBetween('created_at',[datetime(strtotime("-2 weeks")), datetime(time())]);
                } else {
                    $build -> where('created_at','<', datetime(strtotime("-2 weeks")));
                }
            }
        }
        //var_dump($build -> toSql());
        $page = $build ->orderByDesc('id')->paginate((int)$page_size);
        foreach ($page as &$item) {
            //$item['robots'] = $this -> applyService -> getApplyRobotsInfo(RobotApplyConstants::SOP,$item['id']);
            $item['condition_conf'] = $this -> crowSendService->formatConditionToText($item['condition_conf']);
            if($item['crowd_type'] == 2 && !empty($item['speed_text'])){
                $content = $item['content'];
                array_unshift($content, ['msg_type'=>'text','content'=>$item['speed_text']]);
                $item['content'] = $content;
            }
        }
        $list = $page->items();
        $total = $page->total();
        return $this->success('获取成功', ['list' => $list, 'total' => $total]);
    }

    /**
     * 查询统计数据
     */
    #[PostMapping('statistics'), ChPermission('ch:crowd:sending:robot:list')]
    public function statisticsByCrowd()
    {
        $uid = $this->request->input('uid');
        $page_size = $this->request->input('page_size', 15);
        $crowdId = $this->request->input('id');
        $is_loop = $this->request->input('is_loop',0);
        $crowdInfo =  ChCrowdSending::where('id',$crowdId) -> first();
        if(empty($crowdInfo)){
            $this -> error('数据不存在',ErrorCode::NOT_ISSET);
        }
        $statistics = [
            'crowd_total' => $crowdInfo -> crowd_total,
            'custom_total' => $crowdInfo -> custom_total,
            'lose_total' => $crowdInfo -> lose_total,
            'success_total' => ChCrowdSendingSubTask::query()->where('crowd_sending_id',$crowdId)->sum('success_total'),
            'fail_total' => ChCrowdSendingSubTask::query()->where('crowd_sending_id',$crowdId)->sum('fail_total'),
            'complete_total' => ChCrowdSendingSubTask::query()->where('crowd_sending_id',$crowdId)->sum('complete_total'),
        ];
        //查询子任务列表
        $subList = ChCrowdSendingSubTask::query() -> with(['robot'=>function($q){
            $q -> select(['id','nickname','avatar','user_id','login_status','corp_name']);
        }]) -> where('crowd_sending_id',$crowdId) -> where('is_loop',$is_loop) -> get();

        return $this -> success('success',['statistics' => $statistics,'robot_list' => $subList]);
    }



    /**
     * 群发任务发送对象列表
     */
    #[PostMapping('send_record'), ChPermission('ch:crowd:sending:robot:record')]
    public function sendRecord()
    {
        $uid = $this->request->input('uid');
        $page_size = $this->request->input('page_size', 15);
        $taskId = $this->request->input('task_id');
        $robotId = $this->request->input('robot_id');
        //1已发送 0等待中
        $status = $this->request->input('status');
        $taskInfo =  ChCrowdSendingSubTask::query()->with('sending')->where('id',$taskId) -> first();
        if(empty($taskInfo)){
            $this -> error('数据不存在',ErrorCode::NOT_ISSET);
        }
        $build = ChSendRecord::query() -> where('type',$taskInfo->sending -> crowd_type)
            -> where('sub_task_id',$taskId)
            -> where('robot_id',$taskInfo ->robot_id)
            -> select(['to_id','is_room','id','status','failure_reason']);
        if($status == 1){
            $build -> where('status','<>',0);
        }else{
            $build -> where('status',0);
        }
        $recordList = $build -> paginate((int)$page_size);
        $recordList -> each(function($item){
            if($item['status']==3 && empty($item['failure_reason'])){
                $item['failure_reason']='系统发送失败';
            }
            if($item['is_room'] == 1){
                $item['crowd_info'] = ChRoom::query()-> where('room_wxid',$item['to_id']) -> select(['room_avatar_url','id','room_name']) -> first();;
            }else{
                $item['contact_info'] = ChContact::query() -> where('user_id',$item['to_id']) -> select(['avatar','id','nickname','is_wechat','corp_short_name']) -> first();
            }
        });
        $data = [
            'items' => $recordList -> items(),
            'pageInfo' => [
                'total' => $recordList->total(),
                'currentPage' => $recordList->currentPage(),
                'totalPage' => $recordList->lastPage(),
            ],
        ];
        return $this->success('获取成功', $data);
    }



    /**
     * 查询下发企微号
     */
    #[PostMapping('loop/corp'), ChPermission('ch:crowd:sending:robot:list')]
    public function getCorpByLoop()
    {
        $loopId = $this->request->input('id');
        $robotIds = $this -> applyService -> getApplyRobot(SendConfigConstants::SENDING_LOOP,$loopId) -> toArray();
        $robotList = $this -> robotService  -> getRobotListByIds($robotIds);
        $loop =  ChCrowdSendingLoop::where('id',$loopId) -> first();
        if(empty($loop)){
            $this -> error('数据不存在',ErrorCode::NOT_ISSET);
        }
        foreach ($robotList as $key => $robot)
        {
            $robotList[$key]['status'] = $loop -> status;
        }
        return $this -> success('success',$robotList);
    }


    #[PostMapping('loop/list'), ChPermission('ch:crowd:sending:loop:list')]
    public function LoopList()
    {
        $params = $this->request->all();
        $uid = $this->request->input('uid');
        $page_size = $this->request->input('page_size', 15);
        $mainUid = $this->request->input('main_uid');
        $crowd_type = $this->request->input('crowd_type', 1);
        $status = $this->request->input('status', '');

        $where = ['crowd_type' => $crowd_type];
        $accountId = $this->request->input('account_id', 0);
        if (!empty($accountId)) {
            $where[] = ['uid', '=', $accountId];
        } else {
            $where[] = ['main_uid', '=', $mainUid];
        }
        if (!empty($params['group_id'])) {
            $where[] = ['group_id', '=', $params['group_id']];
        }
        if (!empty($params['keyword'])) {
            $where[] = ['title', 'like', "%" . $params['keyword'] . "%"];
        }
        if (not_empty($status)) {
            $where[] = ['status', '=', $params['status']];
        }



        $build = ChCrowdSendingLoop::query()->with(['group' => function ($q) {
            $q->select('id', 'title', 'p_id');
        },'user' => function ($q) {
            $q->select('id', 'nickname');
        }])
            ->select(['id','title','group_id','content','msg_types','status','created_at','send_times_conf',
                'loop_end_time','uid','main_uid','send_times','is_send_loss','exception_type','send_limit_conf','send_limit_type','condition_conf','crowd_type','speed_text'])
            ->where($where);
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $build -> whereBetween('created_at',[$params['start_time'], $params['end_time']]);
        }
        $page = $build->orderByDesc('id')->paginate((int)$page_size);
        foreach ($page as &$item) {
            //$item['robots'] = $this -> applyService -> getApplyRobotsInfo(RobotApplyConstants::SOP,$item['id']);
            //$item['condition_conf'] = $this -> crowSendService->formatConditionToText($item['condition_conf']);
            if($item['crowd_type'] == 2 && !empty($item['speed_text'])){
                $content = $item['content'];
                array_unshift($content, ['msg_type'=>'text','content'=>$item['speed_text']]);
                $item['content'] = $content;
            }
        }
        $list = $page->items();
        $total = $page->total();
        return $this->success('获取成功', ['list' => $list, 'total' => $total]);
    }


    #[PostMapping('operate'), ChPermission('ch:crowd:sending:operate')]
    public function operate()
    {
        $this->validateParam([
            'id' => 'required',
            'status' => 'required',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $status = $this->request->input('status');
        switch ($status) {
            case CrowSendingConstants::PAUSE;
                ChCrowdSending::query()->where('id', $id)->update(['status' => CrowSendingConstants::PAUSE]);
                ChCrowdSendingSubTask::query()->where('is_loop', 0)->where('crowd_sending_id',$id)->update(['status' => CrowSendingConstants::PAUSE]);
                $this->crowSendService->setSendingPauseCache((int)$id);
                break;
            case CrowSendingConstants::SENDING;
                ChCrowdSending::query()->where('id', $id)->update(['status' => CrowSendingConstants::SENDING]);
                ChCrowdSendingSubTask::query()->where('is_loop', 0)->where('crowd_sending_id',$id)->update(['status' => CrowSendingConstants::SENDING]);
                //继续发送
                $this->crowSendService->clearSendingPauseCache((int)$id);
                $this->crowSendService->continueSend((int)$id);
                break;
            case CrowSendingConstants::CANCEL;
                ChCrowdSending::query()->where('id', $id)->update(['status' => CrowSendingConstants::CANCEL]);
                ChCrowdSendingSubTask::query()->where('is_loop', 0)->where('crowd_sending_id',$id)->update(['status' => CrowSendingConstants::CANCEL]);
                break;
        }
        return $this->success('操作成功');
    }


    #[PostMapping('loop/operate'), ChPermission('ch:crowd:sending:loop:operate')]
    public function loopOperate()
    {
        //1执行中  2已完成 3暂停中  4已取消
        $this->validateParam([
            'id' => 'required',
            'status' => 'required',
        ]);
        $uid = $this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        $id = $this->request->input('id');
        $status = $this->request->input('status');
        switch ($status) {
            case CrowSendingConstants::PAUSE;
                ChCrowdSendingLoop::query()->where('id', $id)->update(['status' => CrowSendingConstants::PAUSE]);
                ChCrowdSendingSubTask::query()->where('is_loop', 1)->where('crowd_sending_id',$id)->update(['status' => CrowSendingConstants::PAUSE]);
                break;
            case CrowSendingConstants::SENDING;
                ChCrowdSendingLoop::query()->where('id', $id)->update(['status' => CrowSendingConstants::SENDING]);
                ChCrowdSendingSubTask::query()->where('is_loop', 1)->where('crowd_sending_id',$id)->update(['status' => CrowSendingConstants::SENDING]);
                break;
            case CrowSendingConstants::CANCEL;
                ChCrowdSendingLoop::query()->where('id', $id)->update(['status' => CrowSendingConstants::CANCEL]);
                ChCrowdSendingSubTask::query()->where('is_loop', 1)->where('crowd_sending_id',$id)->update(['status' => CrowSendingConstants::CANCEL]);
                break;
        }
        return $this->success('操作成功');
    }

    #[PostMapping('system/list'), ChPermission('ch:crowd:sending:system:list')]
    public function systemList()
    {
        $list = $this->sendService->getConfigList($this->request->all());
        return $this->success('获取成功', $list);
    }

    #[PostMapping('system/detail'), ChPermission('ch:crowd:sending:system:detail')]
    public function systemDetail()
    {
        $this->validateParam([
            'type' => 'required',
            'robot_id' => 'required',
        ]);

        $mainUid = $this->request->input('main_uid');
        $uid = $this->request->input('uid');
        $robot_id = $this->request->input('robot_id');
        $type = $this->request->input('type');
        $detail = $this->sendService->getConfig($type, $uid, $robot_id);
        return $this->success('获取成功', $detail);
    }

    #[PostMapping('system/save'), ChPermission('ch:crowd:sending:system:save')]
    public function saveSystem()
    {
        $this->validateParam([
            'type' => 'required',
            'robot_ids' => 'required',
            'value' => 'required',
        ]);
        $mainUid = $this->request->input('main_uid');
        $uid = $this->request->input('uid');
        $type = $this->request->input('type');
        $corp_id = $this->request->input('corp_id');
        $robot_ids = $this->request->input('robot_ids');
        $value = $this->request->input('value');
        $robot_ids = !is_array($robot_ids) ? json_decode($robot_ids, true) : $robot_ids;
        foreach ($robot_ids as $robot_id) {
            $this->sendService->saveConfig($type, $uid, $mainUid, $corp_id, $robot_id, $value);
        }
        return $this->success('保存成功', []);
    }

    /**
     * 任务日历按月查询数据
     */
    #[PostMapping('statistics/taskList'), ChPermission('ch:sop:statistics:list')]
    public function statisticsListBuyDay()
    {
        return $this->success($this->crowSendService->getTaskList($this->request->all()));
    }


}